package controllers

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"itchat4go/common"
	m "itchat4go/model"
	s "itchat4go/service"
	"logs"
	"net/http"
	"regexp"
	"strings"
	"time"
)

var regAt = regexp.MustCompile(`^.*@.*郭宇.*$`)
var regGroup = regexp.MustCompile(`^@@.+`)
var regAd = regexp.MustCompile(`(朋友圈|点赞)+`)
var regName = regexp.MustCompile(`^*(晴|郭宇)+`)

func Handler_text(retcode int64, selector int64) {
	if retcode == 0 && selector != 0 {
		//fmt.Printf("selector=%d,有新消息产生,准备拉取...\n", selector)
		wxRecvMsges, err := s.WebWxSync(m.LoginM)
		if err != nil {
			logs.Error(err)
			return
		}

		for i := 0; i < wxRecvMsges.MsgCount; i++ {

			msg := wxRecvMsges.MsgList[i]
			fromName := msg.FromUserName
			content := msg.Content

			if msg.MsgType == 1 {

				/* 普通文本消息 */
				ContactMap2 := *m.ContactMap
				user := ContactMap2[fromName]
				name := user.NickName
				if user.RemarkName != "" {
					name = user.RemarkName
				}
				if strings.Index(content, "<br/>") != -1 {
					cs := strings.Split(content, "<br/>")
					content = cs[1]
				}

				logs.Info("fromName:", fromName)
				logs.Info("name:", name)
				logs.Info("content:", content)

				//有人在群里@我，发个消息回答一下 || 有人跟我聊天,回复一下
				if regAt.MatchString(content) || regName.MatchString(name) {

					content = strings.Replace(content, "@郭宇", "", 1)
					toMess := TuLing(&m.Msg{Name: fromName, Content: content})

					wxSendMsg := m.WxSendMsg{}
					wxSendMsg.Type = 1
					wxSendMsg.Content = "我是郭宇编写的微信机器人，我已帮你通知我的主人，请您稍等片刻，他会跟您联系"
					if toMess.Content != "" {
						wxSendMsg.Content = "机器人回复: " + toMess.Content
					}

					wxSendMsg.FromUserName = msg.ToUserName
					wxSendMsg.ToUserName = fromName
					wxSendMsg.LocalID = fmt.Sprintf("%d", time.Now().Unix())
					wxSendMsg.ClientMsgId = wxSendMsg.LocalID

					go s.SendMsg(wxSendMsg)
				}
			}
		}
	}
}

func SendMsg(toUserName, content string) {
	wxSendMsg := m.WxSendMsg{}
	wxSendMsg.Type = 1
	wxSendMsg.Content = content
	wxSendMsg.FromUserName = m.LoginM.SelfUserName
	wxSendMsg.ToUserName = toUserName
	wxSendMsg.LocalID = fmt.Sprintf("%d", time.Now().Unix())
	wxSendMsg.ClientMsgId = wxSendMsg.LocalID
	go s.SendMsg(wxSendMsg)
}

//图灵机器人
func TuLing(formMess *m.Msg) (toMess m.Msg) {
	p := &struct {
		Key    string `json:"key" xml:"key" from:"key"`
		Info   string `json:"info" xml:"info" from:"info"`
		Loc    string `json:"loc" xml:"loc" from:"loc"`
		Userid string `json:"userid" xml:"userid" from:"userid"`
	}{
		Key:    "4816576622cb40948118180a0d8e21fd",
		Info:   formMess.Content,
		Loc:    "上海市",
		Userid: formMess.Name,
	}

	body, _ := common.Json.Marshal(p)
	resp, err := http.Post("http://www.tuling123.com/openapi/api", "json", bytes.NewReader(body))
	if err != nil {
		logs.Error(err)
		return
	}
	defer resp.Body.Close()
	bodyBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		logs.Error(err)
		return
	}
	res := &struct {
		Code int    `json:"code" xml:"code" from:"code"`
		Text string `json:"text" xml:"text" from:"text"`
		Url  string `json:"url" xml:"url" from:"url"`
	}{}
	common.Json.Unmarshal(bodyBytes, res)

	if res.Text != "" {
		toMess.Content = res.Text
	}

	if res.Url != "" {
		toMess.Content += " " + res.Url
	}
	return
}
